const axios = require("axios");
const XLSX = require("xlsx");
const fs = require("fs");
const path = require("path");

// 配置路径
const inputFilePath = "../Data.xls";
const outputFilePath = "Antonyms_Result.xlsx";

// 读取原始 Excel 中的单词
function getWordsFromExcel(filePath) {
  const workbook = XLSX.readFile(filePath);
  const sheet = workbook.Sheets[workbook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
  return data.slice(1).map(row => row[0]).filter(Boolean);
}

// 加载或新建 Excel 文件
function loadOrCreateWorkbook(filePath) {
  if (fs.existsSync(filePath)) {
    return XLSX.readFile(filePath);
  } else {
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([["Word", "Antonyms JSON"]]);
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    return wb;
  }
}

// 追加结果到 Excel 中
function appendToExcel(word, antonyms, filePath) {
  const workbook = loadOrCreateWorkbook(filePath);
  const sheet = workbook.Sheets[workbook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });

  data.push([word, JSON.stringify(antonyms)]);
  const newSheet = XLSX.utils.aoa_to_sheet(data);
  workbook.Sheets[workbook.SheetNames[0]] = newSheet;
  XLSX.writeFile(workbook, filePath);
}

// 获取已写入的单词，避免重复处理
function getWrittenWords(filePath) {
  if (!fs.existsSync(filePath)) return new Set();
  const workbook = XLSX.readFile(filePath);
  const sheet = workbook.Sheets[workbook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
  return new Set(data.slice(1).map(row => row[0]));
}

// 向 AI 接口请求反义词（返回原始 JSON）
async function getAntonymsFromAI(word) {
  try {
    const response = await axios.post("http://localhost:4587/ai-chat", {
      messages: [{
        role: "user",
        content: `请给出英文单词 "${word}" 的五个反义词，数据返回只返回json格式，格式为{"word":"","Translation":""}，不要给原词，不要给相同的词，最多给五个，如果不够五个就少于五个`
      }]
    });

    let content = response.data?.choices?.[0]?.message?.content?.trim();
    console.log(`API 返回内容: ${content}`);

    content = content.replace(/```json|```/g, '').trim();

    const parsed = JSON.parse(content);
    console.log(`解析后的数据: ${JSON.stringify(parsed)}`);

    return parsed;
  } catch (error) {
    console.error(`❌ 获取 "${word}" 反义词失败:`, error.message);
    return null;
  }
}

// 主函数
async function main() {
  const words = getWordsFromExcel(inputFilePath);
  const writtenWords = getWrittenWords(outputFilePath);
  console.log(`🔍 共 ${words.length} 个单词，将逐个处理，跳过已写入的单词`);

  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    if (writtenWords.has(word)) {
      console.log(`⏩ 已跳过（已存在）：${word}`);
      continue;
    }

    console.log(`\n📌 [${i + 1}/${words.length}] 处理：${word}`);

    let result = null;
    let retryCount = 0;

    while (!result) {
      result = await getAntonymsFromAI(word);
      retryCount++;

      if (!result) {
        console.log(`🔁 第 ${retryCount} 次重试 "${word}"...`);
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }

    appendToExcel(word, result, outputFilePath);
    console.log(`✅ 已写入：${word} → ${JSON.stringify(result)}`);

    if (i < words.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 500));
    }
  }

  console.log("\n🎉 所有单词处理完成！");
}

main();
